package top.wuyang.trywork.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.wuyang.trywork.base.PageBean;
import top.wuyang.trywork.base.R;
import top.wuyang.trywork.dao.TbCpuMapper;
import top.wuyang.trywork.entity.TbCpu;
import top.wuyang.trywork.service.TbCpuService;
import top.wuyang.trywork.vo.PageVO;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbCpuServiceImpl implements TbCpuService {
    private final TbCpuMapper tbCpuMapper;

    private TbCpu queryByCpu(String cpu){
        QueryWrapper<TbCpu> wrapper = new QueryWrapper<>();
        wrapper.eq("cpu", cpu);
        TbCpu tbCpu = tbCpuMapper.selectOne(wrapper);
        return tbCpu;
    }

    @Override
    public R<String> insert(TbCpu tbCpu) {
        // 判断cpu名称是否存在
        TbCpu check = queryByCpu(tbCpu.getCpu());
        if (check != null) {
            return R.fail("该cpu名称已存在", null);
        }
        int i = tbCpuMapper.insert(tbCpu);
        return i == 1 ? R.ok("新增成功", null) : R.fail("新增失败", null);
    }


    @Override
    public R<PageVO<TbCpu>> queryPage(PageBean pageBean, TbCpu tbCpu) {
        IPage<TbCpu> page = new Page<>(pageBean.getPageNumber(), pageBean.getPageSize());
        QueryWrapper<TbCpu> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasText(tbCpu.getCpu()), "cpu", tbCpu.getCpu());
        wrapper.like(StringUtils.hasText(tbCpu.getManufacturer()), "manufacturer", tbCpu.getManufacturer());
        wrapper.like(StringUtils.hasText(tbCpu.getInfo()), "info", tbCpu.getInfo());
        wrapper.like(StringUtils.hasText(tbCpu.getFrequency()), "frequency", tbCpu.getFrequency());
        wrapper.like(StringUtils.hasText(tbCpu.getMaxFrequency()), "max_frequency", tbCpu.getMaxFrequency());
        page = tbCpuMapper.selectPage(page, wrapper);
        return R.ok(page);
    }



    @Override
    public R<TbCpu> queryById(Integer id) {
        TbCpu tbCpu = tbCpuMapper.selectById(id);
        return tbCpu == null ? R.fail("查询失败", null) : R.ok(tbCpu);
    }

    @Override
    public R<String> update(TbCpu tbCpu) {
        // 判断cpu名称是否存在
        TbCpu check = queryByCpu(tbCpu.getCpu());
        if (check != null && !check.getId().equals(tbCpu.getId())) {
            return R.fail("该cpu名称已存在", null);
        }
        int i = tbCpuMapper.updateById(tbCpu);
        return i == 1 ? R.ok("修改成功", null) : R.fail("修改失败", null);
    }


    @Override
    public R<String> delete(Integer id) {
        int i = tbCpuMapper.deleteById(id);
        return i == 1 ? R.ok("删除成功", null) : R.fail("删除失败", null);
    }


}
